using Microsoft.AspNetCore.Mvc;
using ZR.Model.BaseManage.Dto;
using ZR.Model.BaseManage;
using ZR.Service.BaseManage.IBaseManageService;
using ZR.Admin.WebApi.Filters;
using MiniExcelLibs;
using JinianNet.JNTemplate;

//创建时间：2025-04-20
namespace ZR.Admin.WebApi.Controllers.BaseManage
{
    /// <summary>
    /// 物料信息
    /// </summary>
    [Verify]
    [Route("BaseManage/BaseMaterial")]
    public class BaseMaterialController : BaseController
    {
        /// <summary>
        /// 物料信息接口
        /// </summary>
        private readonly IBaseMaterialService _BaseMaterialService;

        public BaseMaterialController(IBaseMaterialService BaseMaterialService)
        {
            _BaseMaterialService = BaseMaterialService;
        }

        /// <summary>
        /// 查询物料信息列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("pageList")]
        [ActionPermissionFilter(Permission = "base:material:list")]
        public IActionResult PageBaseMaterial([FromQuery] BaseMaterialQueryDto parm)
        {
            var response = _BaseMaterialService.GetPageList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询物料信息详情
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <returns></returns>
        [HttpGet("{MaterialId}")]
        [ActionPermissionFilter(Permission = "base:material:query")]
        public IActionResult GetBaseMaterial(string MaterialId)
        {
            var response = _BaseMaterialService.GetInfo(MaterialId);

            var info = response.Adapt<BaseMaterialDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "base:material:add")]
        [Log(Title = "物料信息", BusinessType = BusinessType.INSERT)]
        public IActionResult AddBaseMaterial([FromBody] BaseMaterialDto parm)
        {
            var modal = parm.Adapt<BaseMaterial>().ToCreate(HttpContext);

            var response = _BaseMaterialService.AddBaseMaterial(modal);

            return SUCCESS(response);
        }

        /// <summary>
        /// 更新物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "base:material:edit")]
        [Log(Title = "物料信息", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateBaseMaterial([FromBody] BaseMaterialDto parm)
        {
            var modal = parm.Adapt<BaseMaterial>().ToUpdate(HttpContext);
            var response = _BaseMaterialService.UpdateBaseMaterial(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete")]
        [ActionPermissionFilter(Permission = "base:material:delete")]
        [Log(Title = "物料信息", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteBaseMaterial([FromBody] string[] ids)
        {
            return ToResponse(_BaseMaterialService.Delete(ids));
        }

        /// <summary>
        /// 导出物料信息
        /// </summary>
        /// <returns></returns>
        [Log(Title = "物料信息", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "base:material:export")]
        public IActionResult Export([FromQuery] BaseMaterialQueryDto parm)
        {
            parm.PageNum = 1;
            parm.PageSize = 100000;
            var list = _BaseMaterialService.ExportList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "物料信息", "物料信息");
            return ExportExcel(result.Item2, result.Item1);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost("importData")]
        [Log(Title = "物料信息导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false)]
        [ActionPermissionFilter(Permission = "base:material:import")]
        public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
        {
            List<BaseMaterialDto> list = new();
            using (var stream = formFile.OpenReadStream())
            {
                list = stream.Query<BaseMaterialDto>(startCell: "A1").ToList();
                var lookup = list.ToLookup(p => p.MaterialCode); // 使用MaterialCode进行分组，返回一个Lookup<TKey, TElement>对象
                list = lookup.Select(g => g.First()).ToList(); // 选择每个组的第一个元素并转换为List
            }
            if (list.Count > 1000)
            {
                throw new CustomException("数据最多为1000条");
            }
            //组装数据
            foreach (var item in list)
            {
                item.MaterialId = Guid.NewGuid().ToString().ToUpper();
                item.MaterialCode = item.MaterialCode.Trim();
                item.CreateBy = HttpContext.GetName();
                item.CreateTime = DateTime.Now;
                if (string.IsNullOrEmpty(item.MaterialType)) item.MaterialType = " 其他";
            }

            return SUCCESS(_BaseMaterialService.ImportBaseMaterial(list.Adapt<List<BaseMaterial>>()));
        }

        /// <summary>
        /// 物料信息导入模板下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("importTemplate")]
        [Log(Title = "物料信息模板", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [AllowAnonymous]
        public IActionResult ImportTemplateExcel()
        {
            var result = DownloadImportTemplate(new List<BaseMaterialDto>() { }, "BaseMaterial");
            return ExportExcel(result.Item2, result.Item1);
        }

    }
}